package cn.edu.sjtu.literature.web.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.text.ParseException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import au.com.bytecode.opencsv.CSVWriter;
import cn.edu.sjtu.literature.entity.Literature;
import cn.edu.sjtu.literature.service.LiteratureQuery;
import cn.edu.sjtu.literature.web.util.Constants;
import cn.edu.sjtu.literature.web.view.View;

public class LiteratureExportController extends AbstractController {

	@Override
	public View doAction(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		log.debug("do export literatures");
		
		// validate and bind value
		LiteratureQuery query = validateAndBind(req);
		if (query == null) {
			log.debug("has field error");
			return getView(Constants.VIEW_LITERATURE_EXPORT);
		}
		
		// export literature
		log.debug("validate field successfully and export literature");
		List<Literature> literatures = literatureService.queryLiteratures(query);
		log.debug("export size:" + literatures.size());
		
		// export to csv file
		resp.setContentType("application/csv");
		resp.setHeader("Content-Disposition", "attachment;filename=backup_before_" + Constants.NORMAL_DATE_FORMAT.format(query.getCreatedDateTo()) + ".csv");
		OutputStream os = resp.getOutputStream();
		CSVWriter csvWriter = new CSVWriter(new OutputStreamWriter(os));
		String[] header = new String[] {"id", "issueNo", "title", "categoryId", "categoryName", 
				"author", "authorFirm", "authorContactInfo", 
				"source", "publishDate"};
		csvWriter.writeNext(header);
		String[] nextLine = null;
		for (Literature l : literatures) {
			nextLine = new String[] {"" + l.getId(), l.getIssueNo(), l.getTitle(), "" + l.getCategory().getId(), l.getCategory().getName(), 
					l.getAuthor(), l.getAuthorFirm(), l.getAuthorContactInfo(), 
					l.getSource(), Constants.NORMAL_DATE_FORMAT.format(l.getPublishDate())};
			csvWriter.writeNext(nextLine);
		}
		csvWriter.flush();
		csvWriter.close();
		os.flush();
		os.close();
		
		return null;
	}

	private LiteratureQuery validateAndBind(HttpServletRequest req) {
		String createdDateTo = req.getParameter("createdDateTo");
		
		log.debug("createdDateTo: " + createdDateTo);
		
		boolean hasFieldError = false;
		LiteratureQuery query = new LiteratureQuery();
		if (StringUtils.isBlank(createdDateTo)) {
			req.setAttribute(getFieldErrorKey("createdDateTo"), "不能为空");
			hasFieldError = true;
		} else {
			try {
				query.setCreatedDateTo(Constants.NORMAL_DATE_FORMAT.parse(createdDateTo));
			} catch (ParseException e) {
				req.setAttribute(getFieldErrorKey("createdDateTo"), "格式非法");
				hasFieldError = true;
			}
		}
		req.setAttribute(Constants.LITERATURE_QUERY, query);
		return hasFieldError ? null : query;
	}

}
